package com.taysear.bus;

import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;

import com.taysear.domain.User;
import com.vaadin.Application;
import com.vaadin.service.ApplicationContext.TransactionListener;

/**
 * <code>AppData</code> holds data for one user session.
 * 
 * @author Abdullahi
 */
@SuppressWarnings("serial")
public class AppData implements TransactionListener, Serializable {
	private ResourceBundle bundle;
	private Locale locale; // Current locale
	private User user; // Trivial data model for the user
	private static BusApplication app; // For distinguishing between apps
	private static ThreadLocal<AppData> instance = new ThreadLocal<AppData>();
	private static String portalId;

	public AppData(BusApplication app) {
		AppData.app = app;

		// It's usable from now on in the current request
		instance.set(this);
		portalId = app.getProperty("portalId");
	}

	public static void initLocale(Locale locale, String bundleName) {
		instance.get().locale = locale;
		instance.get().bundle = ResourceBundle.getBundle(bundleName, locale);
	}

	public static Locale getLocale() {
		return instance.get().locale;
	}

	public static String getMessage(String msgId) {
		return instance.get().bundle.getString(msgId);
	}

	public static User getUser() {
		return instance.get().user;
	}

	public static void setUser(User user) {
		instance.get().user = user;
	}

	public static String getPortalId() {
		return portalId;
	}

	public static BusApplication getApp() {
		return app;
	}

	@Override
	public void transactionStart(Application application, Object transactionData) {
		// Set this data instance of this application as the one active in the current thread.
		if (AppData.app == application)
			instance.set(this);
	}

	@Override
	public void transactionEnd(Application application, Object transactionData) {
		// Clear the reference to avoid potential problems
		if (AppData.app == application)
			instance.set(null);
	}
}